package com.bsuir.avareader.dal;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class TextbookDbAdapter {

	private Context mContext;
	private SQLiteDatabase db;
	private AvaReaderDbHelper dbHelper;

	public TextbookDbAdapter(Context context) {
		mContext = context;
	}

	public TextbookDbAdapter open() throws SQLException {
		dbHelper = new AvaReaderDbHelper(mContext);
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	private ContentValues createContentValues(int index, String line) {
		ContentValues values = new ContentValues();
		values.put(AvaReaderDbHelper.INDEX, index);
		values.put(AvaReaderDbHelper.LINE, line);
		return values;
	}

	public long insertLine(int index, String line) {
		ContentValues values = createContentValues(index, line);

		return db.insert(AvaReaderDbHelper.TABLE_TEXTBOOK, null, values);
	}

	public boolean updateLine(long id, int index, String line) {
		ContentValues values = createContentValues(index, line);

		return db.update(AvaReaderDbHelper.TABLE_TEXTBOOK, values,
				AvaReaderDbHelper.KEY_ID + " = " + id, null) > 0;
	}

	public boolean deleteLine(long id) {
		return db.delete(AvaReaderDbHelper.TABLE_TEXTBOOK,
				AvaReaderDbHelper.KEY_ID + " = " + id, null) > 0;
	}

	public Cursor fetchAllLines() throws SQLException {
		return db.query(AvaReaderDbHelper.TABLE_TEXTBOOK,
				new String[] { AvaReaderDbHelper.LINE }, null, null, null,
				null, " order by " + AvaReaderDbHelper.INDEX);
	}

	public Cursor fetchLine(int index) {
		return db.query(AvaReaderDbHelper.TABLE_TEXTBOOK,
				new String[] { AvaReaderDbHelper.LINE },
				AvaReaderDbHelper.KEY_ID + " = " + index, null, null, null,
				null);
	}
}
